package com.fulihui.systemcore.integration.baidu;

import com.alibaba.fastjson.JSONObject;
import com.fulihui.systemcore.dto.AreasDTO;
import com.fulihui.systemcore.dto.PhoneRegLocDTO;
import com.fulihui.systemcore.repository.AreasRepository;
import org.near.toolkit.common.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Optional;

/**
 * 手机归属地百度 API
 *
 * @author Willard.Hu on 2016/11/29 0029.
 */
@Component
public class PhoneRegLocBaiduApi {
    private static final String API_URL = "http://apis.baidu.com/showapi_open_bus/mobile/find?num=";
    @Value("${baidu.apistore.key}")
    private String          apikey;
    @Autowired
    private AreasRepository areasRepository;

    public PhoneRegLocDTO query(int num) {
        PhoneRegLocDTO dto = null;
        StringBuilder sbf = new StringBuilder();
        try {
            URL url = new URL(API_URL + num);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", apikey);
            connection.connect();
            InputStream is = connection.getInputStream();
            String result;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
                String strRead;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
            if (!result.isEmpty()) {
                dto = toDTO(JSONObject.parseObject(result), num);
            }
            return dto;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private PhoneRegLocDTO toDTO(JSONObject jsonObject, int num) {
        if (jsonObject == null) {
            return null;
        }

        if (jsonObject.getInteger("showapi_res_code") != 0) {
            throw new RuntimeException(jsonObject.getString("showapi_res_error"));
        }
        JSONObject body = jsonObject.getJSONObject("showapi_res_body");
        PhoneRegLocDTO dto = new PhoneRegLocDTO();
        dto.setPrefix(num);
        String provinceCode = body.getString("provCode");
        if (provinceCode == null) {
            return null;
        }
        dto.setProvince(provinceCode);
        dto.setProvincename(body.getString("prov"));
        List<AreasDTO> list = areasRepository.queryCityList(provinceCode);
        if (!CollectionUtils.isEmpty(list)) {
            final String cityName = body.getString("city");
            if (StringUtil.isBlank(cityName)) {
                AreasDTO item = list.get(0);
                dto.setCity(item.getCode());
                dto.setCityname(item.getAreaName());
            } else {
                // 查询到的城市名，通过全名称和短名称对比
                Optional<AreasDTO> optional = list.stream().filter(it ->
                        it.getAreaName().equals(cityName) || it.getShortName().equals(cityName))
                        .findFirst();
                if (optional.isPresent()) {
                    AreasDTO item = optional.get();
                    dto.setCity(item.getCode());
                    dto.setCityname(item.getAreaName());
                }
            }
        }
        dto.setSuit(String.valueOf(num / 10000));
        dto.setSupplier(body.getString("name"));
        return dto;
    }

}
